package com.transfer.kernel;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class TextTransfer {

	private int itask = 0;
	private String fsrc;
	private String ftarget;
	private List<File> tasks = new ArrayList<File>();
	
	public TextTransfer(File fsrc, File ftarget) {
		// TODO Auto-generated constructor stub
		this.fsrc = fsrc.getAbsolutePath();
		this.ftarget = ftarget.getAbsolutePath();
		this.putTask(fsrc);
	}

	private void putTask(File task) {
		// TODO Auto-generated method stub
		if (task.isFile() && task.getName().endsWith(".java")) {
			tasks.add(task);
		}else if(task.isDirectory()){
			String path = task.getAbsolutePath();
			path = path.replace(fsrc, ftarget);
			new File(path).mkdir();
			File[] list = task.listFiles();
			for (File file : list) {
				putTask(file);
			}
		}
	}

	public boolean hasTask() {
		// TODO Auto-generated method stub
		return itask < tasks.size();
	}

	public String doTask() throws IOException {
		// TODO Auto-generated method stub
		File file = tasks.get(itask++);
		String path = file.getAbsolutePath().replace(fsrc, ftarget);
		File ofile = new File(path);
		InputStreamReader reader = new InputStreamReader(new FileInputStream(file),"GBK");
		OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(ofile), "UTF-8");
		BufferedReader bReader = new BufferedReader(reader);
		BufferedWriter bWriter = new BufferedWriter(writer);
		String line = null;
		while((line = bReader.readLine())!=null){
			bWriter.write(line+"\r\n");
		}
		bWriter.close();
		bReader.close();
		writer.close();
		reader.close();
		return path;
	}

}
